﻿
var gdViewModel;
var MailKind = "收件箱";//标记读取类型
var EmailAttachmentTrueName=null;//附件的名称
var EmailAttachmentUrl = null;//附件的服务器路径
var attachmentlistss = null; //邮件的附件，查看“草稿箱”时使用
var EmailAttchStr = null;//EmailAttchStr附件的 ID组装


$(function () {


    //富文本编辑器定义
    var ue = new baidu.editor.ui.Editor();
    txtbIUserID = $("#txtbIUserID");//收件人
    txtbSTitle = $("#txtbSTitle");//邮件主题
    $("#txtbID").val("0");
    ue.render("editor");   //这里填写要改变为编辑器的控件id写信

    //左边栏active
    $("#inbox-content ul li").click(function () {
        $("#inbox-content ul li").filter(".active").removeClass("active");
        $(this).addClass("active");

    });

    var options = {

        hidId: $("#txtbID"),
        pageSize: 10,//分页大小
        frmElement: $("#formMail"),////写信页面的ID
        SaveUpdateBtn: $("#btnSaveOrUpdateModel"),//发送邮件按钮Id 
        //默认的排序方式
        defaultOrderBy: "ID ",

        //节点数据
        NodeValue: ko.observable({
            Id: '',
            SaveOrSend: '',
            SSenderNo: '',
            SSenderName: '',
            SRecName: '',
            STitle: '',
            DSendtime: new Date(),
            IEmailType: '',
            IIsDestroyAffterRead: '',
            IIsCancel: '',
            SSendIp: '',
            STitle: '',
            SRecNo: '',
            SContent: '',
            SAttachmentName: '',
            IType: '',
            SUrl:'',
            IIsRead: '',
            IIsDeleteFlag: 0,
            IIsExistAttchment: ''

        }),
       

        //邮件查询URL
        dataQueryUrlAccessor: function () {

            if (MailKind == "发件箱" || MailKind == "写信") {
                return '/api/EmailExt/SenderCurrentSysMail/';
            }
            else if (MailKind == "收件箱") {
                return '/api/EmailExt/GetCurrentSysMail/';
            }
            else if (MailKind == "草稿箱") {
                return '/api/EmailExt/DraftCurrentSysMail/';
            }
        },
        AddBefore: function () {

            gdViewModel.MailDetailDiv.hide();//隐藏邮件详细
            gdViewModel.gridDiv.hide();     //隐藏邮件列表
            gdViewModel.NodeDiv.show();     //显示写信页面   
            return true;
        },
        //添加用户URL
        dataAddUrlAccessor: function () {           
        },
        beforeData: function (item) {

            //处理记录的邮件数量
            var UnReadCount = item.UnReadDataCount;  //取到当前用户未读邮件的总数
            var tempdata;//临时变量记录当前的邮件数量
            if (UnReadCount == null || UnReadCount == "")
                tempdata = 0;
            else
                tempdata = UnReadCount;
            gdViewModel.ShowUnRead(tempdata); //调用计算未读邮件封数函数
            return true;
        },
        dataUpdateAccessor: function (result) {           
        },
        //查看选中的邮件详情的URL
        dataNodeSelect: function (id) {
            return "/api/EmailExt/DetailMail/" + id;
        },
        dataDeleteAccessor: function (data) {

            var mailIDs = "";//定义选中的邮件Id串
            var check = $("input:checked");  //得到所有被选中的checkbox
            check.each(function (i) {        //循环拼装被选中项的值
                if ($(this).val() != "on") {
                    mailIDs = mailIDs + ',' + $(this).val();
                }
            });
          
            //tempKind记录并传递邮件类型:0收件箱类型，1表示发件箱和草稿箱
            var tempKind = 0;//tempKind为0表示为收件箱
            if (MailKind == "收件箱") {
                tempKind = 0;
            }
            else//发件箱和草稿箱
            {
                tempKind = 1;
            }
            mailIDs = dropRsplit(mailIDs, ",");//清除多余的分割号
            if (mailIDs != "") {//返回删除邮件的url
                return appendQueryString("/api/EmailExt/DeleteEmail/", { ids: mailIDs, EmailKind: tempKind });
            } else
                return "";
        },
        showBefore: function () {
        },
        changeEnd: function (data, event) {

            //把self改为gdViewModel
            gdViewModel.NodeDiv.hide();     //隐藏写信页面     
            gdViewModel.MailDetailDiv.hide();//隐藏邮件详细
            gdViewModel.gridDiv.show();     //显示邮件列表
            //对话框保存的后置事件  
        },
        initEd: function () {
            gdViewModel.gridDiv = $("#ShowMailList");//邮件列表
            gdViewModel.MailDetailDiv = $("#MailDetail");//邮件详细
            gdViewModel.NodeDiv = $("#MailMessageModal");//写信/回信页面获取
            gdViewModel.chosenMailData = ko.observable();
            gdViewModel.showMailHeader();//显示邮件头部信息

            //11.20 by lzq
            var vbEmail = $("#vbEmail").val();//用于首页转跳获取点击Email的Id
            var data = { Id: vbEmail, IEmailType: 1 };
            if (vbEmail != -1) {
                gdViewModel.goToMail(data); 显示邮件详细信息
                $("#vbEmail").val("-1");
            }  //end

        },
        showDlgBefore: function () {
            gdViewModel.loginState(true);
        },
        showDetailEnd: function (data) {
            if (data != null) {
                txtbIPartID.val(data.IPartId);
                txtbSSex.val(data.SSex);
                $('#txtbDBirth').val(Tms.formatDateTime(data.DBirth));
                $('#txtbIPartID').val(data.IPartId);
                gdViewModel.loginState(false);
            }

        }



    };



    gdViewModel = new gridViewModel(options);
    gdViewModel.loginState = ko.observable(true);
    gdViewModel.mailvalue = ko.observable(0);
    gdViewModel.mailHeader = ko.observable();//邮件头部
    gdViewModel.AttchmentrecordSet = ko.observableArray(); //被选中邮件的附件数据集
    gdViewModel.ShowUnRead = ko.observable();//显示未读邮件信息


    //验证收件人信息是否满足指定的格式  add by yzp
    gdViewModel.ReciverValidate = function () {

        var bol = 0;
        var reg = /^([a-zA-Z]{2,10}|[\u4e00-\u9fa5]{2,10})+<([0-9]{3,8})+>$/;
        var Reciver = txtbIUserID.val();
        var SRecNameData = Reciver.split(';');//剪切成收件人姓名数组      
        for (var i = 0; i < SRecNameData.length - 1; i++) {
            if (reg.test(SRecNameData[i])) {
                bol = 1;
            }
            else {
                bol = 0;
            }
        }
        return bol;
    }


    //取写信页面的公共数据  add by yzp
    gdViewModel.Commondata = function () {

        if (txtbIUserID.val() == null || txtbIUserID.val() == "") {
            this.NodeValue().SRecNo = null;  //收件人的编号和姓名
        }
        else {
            this.NodeValue().SRecNo = txtbIUserID.val();  
        }
        this.NodeValue().SAttachmentName = EmailAttachmentTrueName; //附件名
        this.NodeValue().SUrl = EmailAttachmentUrl;//附件的服务器路径
        this.NodeValue().STitle = $("#txtbSTitle").val();//获取标题
        this.NodeValue().SContent = ue.getContent();//信件的内容
        this.NodeValue().IIsDeleteFlag = 0;//0表示发件人没删除所发信息
    }


    // 显示已读未读  修改于10.24 by yzp
    gdViewModel.isReading = function (item) {

        if (item != null)
        {          
            $("#MailsListMessage").hide();
        }
        var result = item.IIsRead;//获取是否已读       
        //console.log(result);
        if (typeof (result) != 'undefined') {           
            if (MailKind == "收件箱") {
                if (result == 1) {
                    return "";
                }
                return "noRead";
            }

        }
        return "";
                
    }


    //显示附件图标
    gdViewModel.IsShowAttachmentIcon = function (item) {

        var result = item.IIsExistAttchment;//获取附件标志
        //console.log(result);
        if (typeof (result) != 'undefined') {
            if (result == 0) {
                return "unshowIcon";
            }
        }
        return "";
    }


    //绑定当前的属性 是SSenderName或者SRecName
    gdViewModel.GetText = function (SSenderName, SRecName) {
        if (MailKind == "发件箱" || MailKind == "草稿箱") {
            if (SRecName == "" || SRecName == null) {
                return "(收件人未填)";
            }
            return SRecName;
        }
        else
            return SSenderName;
    };


    //点击写信按钮写信      
    gdViewModel.NewLetter = function () {
        //test1133
        MailKind = "写信";
        $("#txtbIUserID").val("");//将收件人的内容置为空
        $("#txtbSTitle").val("");//将标题里面的内容置为空
        ue.setContent("");
        //test1133
        $("#Apenddexid").hide();
        $("#existedAttachements").empty();//清空附件列表
        $("#bootstrapped-fine-uploader .qq-upload-list").empty();
        $(".show-next").show();
        options.AddBefore();
        gdViewModel.showMailHeader();//处理头部信息+

    }


    //存草稿，点击“存草稿”的时候使用  add by yzp 
    gdViewModel.SavaDraft = function () {

        gdViewModel.Commondata();  //取数据
        this.NodeValue().IEmailType = 0;//存为草稿
        if (this.NodeValue().SRecNo != null) {
            var bol = gdViewModel.ReciverValidate();  //验证收件人书写格式是否合格
            if (bol != 1) {
                this.NodeValue().SRecNo = null;
            }
            else {
                this.NodeValue().SRecNo = txtbIUserID.val();
            }
        }
        var URL = null;  //url地址
        if (options.hidId.val() == 0 || options.hidId.val() == "0" || options.hidId.val() == null) //说明是新邮件或者是草稿，现在发送
        {
            URL = "/api/EmailExt/SendEmail/";//第一次插入草稿
        }
        else {
            URL = "/api/EmailExt/UpDateMail/";//再次更新邮件（村为草稿或者发送
        }
        $.ajax({
            url: URL,
            type: "Post",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(this.NodeValue()),
            success: function (data, text) {

                //toast用于提示框：提示邮件已保存为草稿
                $.toast({
                    text: "邮件已保存为草稿! ",
                    heading: 'Note',
                    position: 'top-right',
                    type: 'info',
                    hideAfter: 2000,
                })

                self.highLighNodeId = data.Id;
                options.hidId.val(data.Id);
                gdViewModel.init();

            }
            , error: function (XMLHttpRequest, textStatus, errorThrown, d) {
                alert(XMLHttpRequest.responseText);
            }
        }).always(function () {
            gdViewModel.SaveUpdateBtn.removeAttr("disabled");//设置发送按钮ID生效
            $("#btnSaveAsDraftModel").removeAttr("disabled");//设置保持草稿按钮ID生效
            gdViewModel.dialog.modal("hide");
        });


    }


    //回信需修改Undefined
    gdViewModel.Repply = function () {

        $("#SimInfo").hide();//头部信息隐藏
        options.AddBefore();
        if (MailKind == "收件箱") {

            if (options.NodeValue().Id != null && options.NodeValue().Id != "" && typeof (options.NodeValue().Id) != undefined) {
                $("#txtbIUserID").val(options.NodeValue().SSenderName + "<" + options.NodeValue().SSenderNo + ">;"); //回信，绑定收件人
            }
            else {
                $("#txtbIUserID").val("输入正确的收件人");
            }
            if (typeof (options.NodeValue().STitle) != "undefined") {
                $("#txtbSTitle").val("Re:" + options.NodeValue().STitle); //邮件主题
            }
        }
        if (MailKind == "发件箱") {

            var SRecData = '';
            var SRecNameData = options.NodeValue().SRecName.split(';');//剪切成收件人姓名数组
            var SRecNoData = options.NodeValue().SRecNo.split(';');//剪切成收件人编号数组
            for (var i = 0; i < SRecNameData.length - 1; i++) {
                SRecData = SRecData + SRecNameData[i] + "<" + SRecNoData[i] + ">;";
            }
            $("#txtbIUserID").val(SRecData);

            if (typeof (options.NodeValue().STitle) != "undefined") {
                $("#txtbSTitle").val("Re:" + options.NodeValue().STitle); //邮件主题
            }
        }
    }


    //发送邮件  点击“发送”按钮的时候执行
    gdViewModel.SendNormalEmail = function () {

        //输入验证，验证成功，则传入后台
        if (gdViewModel.frmElement.valid()) {
            //根据不同的hidID，决定应当是新增还是更新
            var URL = null;
            if (options.hidId.val() == 0 || options.hidId.val() == "0" || options.hidId.val() == "") {
                URL = "/api/EmailExt/SendEmail/";
            }
            else {
                URL = "/api/EmailExt/UpDateMail/";
            }
            var bol = gdViewModel.ReciverValidate();  //验证收件人书写格式是否合格
            if (bol == 1) {
                this.NodeValue().IEmailType = 1;//存为草稿
                gdViewModel.Commondata();//取页面上的数据
                $.ajax({
                    url: URL,
                    type: "Post",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(this.NodeValue()),
                    success: function (data, text) {


                        //邮件发送成功提示框
                        $.toast({
                            text: "邮件发送成功! ",
                            heading: 'Note',
                            position: 'top-right',
                            bgColor: '#2ecc71',
                            textColor: '#fff',
                            hideAfter: 2000,
                        })
                        self.highLighNodeId = data.Id;
                        //重新设置转跳至发件箱
                       
                        //改变左边栏状态为发件箱
                        gdViewModel.ChangeEmailBox(MailKind);
                        options.hidId.val(data.Id);
                        gdViewModel.goToFolder(MailKind);// 查看邮件列表
                        gdViewModel.changeEnd(options.hidId.val());//后置事件
                        gdViewModel.init();//初始化查询
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown, d) {
                        alert(XMLHttpRequest.responseText);
                    }
                }
                ).always(function () {

                    gdViewModel.SaveUpdateBtn.removeAttr("disabled");//设置发送按钮ID生效
                    $("#btnSaveAsDraftModel").removeAttr("disabled");//btnSaveAsDraftModel设置保持草稿按钮ID生效
                    EmailAttachmentTrueName = null;//附件名置空
                    EmailAttachmentUrl = null; //附件URL置空
                    gdViewModel.dialog.modal("hide");
                    //处理发送邮件过后页面上的附件信息
                    $("#Apenddexid").hide();//附件隐藏
                    $("#bootstrapped-fine-uploader .qq-upload-list").empty();//上传信息清空
                    $(".show-next").show();//附件图标显示

                });
            }
            else {
                alert("收件人信息格式出错了，请按  '姓名<编号>;'  格式填写！");
                return false;
            }
        }
    }


    //处理邮件头部信息8.29 
    gdViewModel.showMailHeader = function () {

        var folder = MailKind;//传递邮件类型
        var tmpStr = "";
        switch (folder) {
            case '收件箱':
                //需要显示:收件箱 (共 5 封，其中 未读邮件 4 封)
                tmpStr = "收件箱 (共 <u><strong> "
                + gdViewModel.totalCount() +

                " </strong></u>封,其中未读邮件 <u><strong>"
                + gdViewModel.ShowUnRead() + "</strong></u>封)";
                if (gdViewModel.totalCount() == 0) {

                    $("#MailsListMessage").empty();
                    var showwords = "<p class='center font-md' style='margin-top:20px'>" + "当前" + MailKind + "没有邮件" + "</p>";
                    $("#MailsListMessage").append(showwords);
                    $("#MailsListMessage").show();
                }
                break;

            case '发件箱':
                //需要显示:发件箱 (共 5 封)
                tmpStr = "发件箱 (共 <u><strong> "
                + gdViewModel.totalCount() + " </strong></u>封)";
                if (gdViewModel.totalCount() == 0) {

                    $("#MailsListMessage").empty();
                    var showwords = "<p class='center font-md' style='margin-top:20px'>" + "当前" + MailKind + "没有邮件" + "</p>";
                    $("#MailsListMessage").append(showwords);
                    $("#MailsListMessage").show();
                }
                break;

            case '草稿箱':
                //需要显示:草稿箱 (共 ?封)
                tmpStr = "草稿箱 (共 <u><strong> "
                + gdViewModel.totalCount() + "</strong></u> 封)";
                if (gdViewModel.totalCount() == 0) {
                    $("#MailsListMessage").empty();
                    var showwords = "<p class='center font-md' style='margin-top:20px'>" + "当前" + MailKind + "没有邮件" + "</p>";
                    $("#MailsListMessage").append(showwords);
                    $("#MailsListMessage").show();
                }
                break;

            default:
                break;

        }
        gdViewModel.mailHeader(tmpStr);
    }


    // 查看不同邮件列表
    gdViewModel.goToFolder = function (folder) {

        if (folder != null && folder != "" && typeof (folder) != 'undefined') {
            MailKind = folder;
            IsShowSimpleEmailInfo = 0;
        }
        //test1123
        //清空写信页面上的数据
        $("#Apenddexid").hide();//附件隐藏
        $("#bootstrapped-fine-uploader .qq-upload-list").empty();//上传清空
        $(".show-next").show();//附件标志显示

        $("#MailMessageModal").hide();//写信页面隐藏
        gdViewModel.init();
        gdViewModel.initEd();
        $("#MailDetail").hide();//邮件详细隐藏
        $("#ShowMailList").show();  //邮件列表显示
        gdViewModel.pageIndex(1);

    }


    //显示邮件详情  
    gdViewModel.goToMail = function (mail) {
        gdViewModel.GetSelectedEmailAttchment(mail.Id)
        $.ajax({
                url: '/api/EmailExt/DetailMail/' + mail.Id,
                type: 'GET',
                success: function (data, text) {
                    gdViewModel.NodeDiv.hide(); //写信页面隐藏   by zjb
                    gdViewModel.gridDiv.hide();//邮件列表隐藏
                    //self.MailDetailDiv.show();//邮件详细显示
                    if (mail.IEmailType == 1 && MailKind == "发件箱") {

                        gdViewModel.MailDetailDiv.show();//邮件详细显示
                        if (data != "") {
                            data.Data.SContent = data.Ext;//邮件页面获取从后台传递内容
                            gdViewModel.NodeValue(data.Data);
                        }
                    }
                    else if (mail.IEmailType == 1 && MailKind == "收件箱") {
                        gdViewModel.MailDetailDiv.show();//邮件详细显示
                        if (data != "") {
                            var tempName = data.CurrentUserNames;//从后台获取当前用户名
                            var tempNo = data.CurrrentUserNos;//从后台获取当前用户编号
                            data.Data.SRecName = tempName;
                            data.Data.SRecNo = tempNo;
                            data.Data.SContent = data.Ext;
                            gdViewModel.NodeValue(data.Data);
                        }
                    }
                    if (mail.IEmailType == 0 && MailKind == "草稿箱") {
                        gdViewModel.NodeDiv.show(); //写信页面显示   by zjb
                        if (data != "") {
                            var SRecData = '';//拼接姓名和编号字段
                            if (data.Data.SRecName != null)  //update by yzp   避免没有收件人信息时报错问题
                            {
                                var SRecNameData = data.Data.SRecName.split(';')
                                var SRecNoData = data.Data.SRecNo.split(';');
                                for (var i = 0; i < SRecNameData.length - 1; i++) {
                                    SRecData = SRecData + SRecNameData[i] + "<" + SRecNoData[i] + ">;";
                                }
                            }
                            $("#txtbIUserID").val(SRecData);//获取后台传递的收件人姓名编号
                            $("#txtbSTitle").val(data.Data.STitle);//获取后台传递的标题

                            //add by yzp  test
                            gdViewModel.GetSelectedEmailAttchment(data.Data);
                            $("#existedAttachements").empty();//先清空先前的内容
                            if (attachmentlistss != null && attachmentlistss!="") {
                                EmailAttchStr = "Accr";
                                $("#Apenddexid").removeClass("hidden");  //添加附加的div显示
                                $("#Apenddexid").show();  //添加附加的div显示
                              
                                for (var item in attachmentlistss) {
                                    $("#existedAttachements").append("<tr id=" + EmailAttchStr + attachmentlistss[item].Id + "><td>" + attachmentlistss[item].SAttachmentName + "&nbsp;&nbsp;&nbsp;<i class='glyphicon glyphicon-remove' onclick='onDataDeleteEmailAttach(" + attachmentlistss[item].Id + ")'></i></td><tr>");
                                }
                            }
                            $("#txtbID").val(data.Data.Id);
                            options.NodeValue().Id = data.Data.Id;
                            ue.setContent(data.Ext);//将获取的内容放到百度编辑框里面
                        }
                    }
                },
                error: function (data) {

                    alert("读取邮件数据出错！");
                }
        });
    }


    //获取所查看邮件的所有附件
    gdViewModel.GetSelectedEmailAttchment = function (emailID) {
        $.ajax({
            url: '/api/EmailExt/EmailAttachmentInfo?emailId=' + emailID,
            type: 'POST',
            success: function (result) {
                if (result == null || result == "") {
                    $("#attachmentid").hide();  //如果没有附件，就不显示附件的div  修改于10.28
                }
                gdViewModel.AttchmentrecordSet(result);//获取附件信息
                attachmentlistss = null;  //先清空以前的数据
                attachmentlistss = result;

            }
        })

    }


    //从详细邮件返回邮件列表 by zjb  2014/7/28
    gdViewModel.goToList = function () {

        $("#SimInfo").show();//头部信息显示

        gdViewModel.MailDetailDiv.hide();//邮件详细隐藏
        gdViewModel.NodeDiv.hide(); //写信页面隐藏   by zjb
        gdViewModel.goToFolder(MailKind);
        gdViewModel.gridDiv.show(); //邮件列表显示
        //这个地方写 test1123
        //清空写信页面上的数据
        $("#Apenddexid").hide();
        $("#bootstrapped-fine-uploader .qq-upload-list").empty();
        $(".show-next").show();


    }


    //begin 全选(选中和取消)列表处理
    //全选列表
    gdViewModel.checkAllMail = function () {
        $('.btn-default  :checkbox ').prop('checked', true).parent().addClass('checked');
        $('.checkboxs tbody :checkbox').prop('checked', true).parent().addClass('checked');

    }
    //全不选列表
    gdViewModel.unCheckAllMail = function () {

        $('.btn-default  :checkbox ').prop('checked', false).parent().removeClass('checked');
        $('.checkboxs tbody :checkbox').prop('checked', false).parent().removeClass('checked');
    }

    //通过checkbox全选、全不选
    gdViewModel.toggleChecks = function (a, e, c, d) {
        var tmpItem = $('#tableCheck');
        if (tmpItem[0].className == "checked") {
            //已被选中，改为不选
            gdViewModel.unCheckAllMail();
        } else {

            //未被选中,改为选中
            gdViewModel.checkAllMail();
        }
        //阻止事件冒泡代码
        if (e && e.stopPropagation)
            //因此它支持W3C的stopPropagation()方法
            e.stopPropagation();
        else
            //否则，我们需要使用IE的方式来取消事件冒泡
            window.event.cancelBubble = true;
        return false;
    }
    // end  全选(选中和取消)列表处理


    //改变显示当前激活的邮箱(主要是针对发件箱处理)//2015.1/14
    gdViewModel.ChangeEmailBox = function (MailKind) {

        switch (MailKind) {
            case '发件箱':
                break;
            case '收件箱':
            case '写信':
                $("#firstID").removeClass("active");
                $("#secondid").addClass("active");
                break;
            case '草稿箱':
                $("#thirdid").removeClass("active");
                $("#secondid").addClass("active");
                break;

        }
        MailKind = '发件箱';//再次设置为发件箱
        gdViewModel.goToFolder(MailKind);//跳转页面到列表
    }

    gdViewModel.init();//初始化
    ko.applyBindings(gdViewModel);


    $("#inbox-content ul li").first().addClass("active");//默认收件箱选中

    //输入收件人姓名联想提示
    $("#txtbIUserID").typeahead({
        source: function (query, process) {
            var txtbIRevType = $("#txtbIRevType");
            var strURL = "/Api/EmailExt/GetAllTypeUser?Type=" + txtbIRevType.val();
            if (txtbIRevType.val() == "" || txtbIRevType.val() == "0")
                return;//空处理 
            $.ajax({
                url: strURL,
                type: 'POST',
                dataType: 'JSON',
                async: true,
                data: 'Name=' + query,
                success: function (data) {
                    var arr = [];
                    for (i in data) {//构建 查询时显示 某某<编号>;
                        arr.push(data[i].SName + "<" + data[i].SNo + ">" + ";");
                    }
                    process(arr);
                }
            });
        }

    });


    //验证页面上的 name="txtbIUserID"和name="txtbSTitle"
    options.frmElement.validate({
        rules: {
            txtbIUserID: { required: true }, txtbSTitle: { required: true, maxlength: 200 }
        },
        messages: {
            txtbIUserID: { required: "<font color='red'>必填项</font>" }, txtbSTitle: { required: "<font color='red'>必填项</font>", maxlength: "<font color='red'>最大长度为200</font>" }
        }
    });


    $("#inbox-table [rel=tooltip]").tooltip();
    $(".table-wrap [rel=tooltip]").tooltip();

    $("#inbox-table input[type='checkbox']").click(function () {//单击选中要删除的邮件
        alert($(this).html());
        $(this).parent().parent().parent('tr').toggleClass("highlight", $(this).checked);
        alert(this);
    });

    //附件显示点击图标：显示或者隐藏
    $(".show-next").click(function () {
        var css = $("#Apenddexid").css("display");
        if (css == "block") {
            $("#Apenddexid").hide();
        } else if (css == "none") {
            $("#Apenddexid").show();
        }

    });
    //写信部分js end

});

//删除选中的附件，查看“草稿箱”的邮件详细信息时调用
function onDataDeleteEmailAttach(ID) {
    var AttachId = EmailAttchStr + ID;
    $.ajax({
        url: "/api/EmailExt/DeleteChoosenAttach?ID=" + ID,
        type: "POST",
        success: function () {
            $("#" + AttachId).empty();
        }
    })
}

//文件上传
$("#bootstrapped-fine-uploader").fineUploader({
    request: {
        endpoint: '/Api/EmailExt/EmailAttchmentUpload/',
    },
    text: {
        uploadButton: '<span class="btn-label"><i class="glyphicon glyphicon-open"></i></span> 添加附件'
    },
    validation: {
        allowedExtensions: ['jpeg', 'jpg', 'gif', 'png', 'doc', 'docx', 'xls', 'docm'
            , 'xlsx', 'pptx', 'ppt', 'zip', 'rar', 'pdf', 'wps', 'et', 'dps', 'txt'],
        sizeLimit: 10485760 // 10MB = 10 * 1024kb * 1024 bytes
    },
    template:
        '<pre class="qq-upload-drop-area span12"><span>{dragZoneText}</span></pre>' +
        '<div class="qq-upload-button  " style="width: auto;padding: 0 ; margin-top:5px; ">{uploadButtonText}</div>' +
        '<span class="qq-drop-processing"></span>' +
        '<ul class="qq-upload-list " style="margin-top: 10px; text-align: center; width:200px"></ul>'
    ,
    callbacks: {
        onSubmit: function (id, fileName) {
            $messages.append('<div id="file-' + id + '" class="alert" style="margin: 20px 0 0"></div>');
        },
        onUpload: function (id, fileName) {
            $('#file-' + id).addClass('alert-info').html('<img src="~/Images/loading.gif" alt="Initializing. Please hold."> ' +
                'Initializing ' + '“' + fileName + '”');
        },
    },
    classes: {
        success: 'alert alert-success',
        fail: 'alert alert-error'
    },
    debug: true
}).on('complete', function (event, id, fileName, responseJSON) {
    if (responseJSON.success) {
        EmailAttachmentTrueName = EmailAttachmentTrueName + ";" + responseJSON.trueAttachName; //获取附件的附件名
        EmailAttachmentUrl = EmailAttachmentUrl + ";" + responseJSON.AttachwebFile;//获取附件的服务器地址
    }
})
